package cn.kingyea.bigdata.yarn;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest;
import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.GetApplicationReportRequestPBImpl;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.kingyea.utils.LoginUtil;

/**
 * fusioninsight yarn demo
 * @author hshe
 *
 *test ..TODO
 *
 *failure .client....
 */
public class YarnTest {

	private static String PRINCIPAL = "username.client.kerberos.principal";
	private static String KEYTAB = "username.client.keytab.file";
	private static Logger LOG = LoggerFactory.getLogger(YarnTest.class);
	
	public static Boolean login(Configuration conf) { 
        boolean flag = false; 
 
        try { 
            // security mode 
            if ("kerberos".equalsIgnoreCase(conf 
                    .get("hadoop.security.authentication"))) { 
                conf.set(PRINCIPAL, conf.get("username.client.kerberos.principal")); 
                // keytab file 
                conf.set(KEYTAB, System.getProperty("user.dir") + File.separator 
                        + "conf" + File.separator + conf.get("username.client.keytab.file")); 
 
                         // kerberos path 
                         String krbfilepath = System.getProperty("user.dir") 
                                            + File.separator + "conf" + File.separator + "krb5.conf"; 
                         System.setProperty("java.security.krb5.conf", krbfilepath); 
 
                         flag = loginFromKeytab(conf); 
                } 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return flag; 
 
    } 
         
	public static Boolean loginFromKeytab(Configuration conf) {
		boolean flag = false;
		UserGroupInformation.setConfiguration(conf);
		try {
			if (UserGroupInformation.isLoginKeytabBased()) {
				UserGroupInformation.getLoginUser().reloginFromKeytab();
				LOG.info("Relogin successfully.");
			} else {
				UserGroupInformation.loginUserFromKeytab(conf.get(PRINCIPAL), conf.get(KEYTAB));
				LOG.info("Login successfully.");
			}

			flag = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	
	@Test
	public void main1() {
		try {
			  
//			client.getAllQueues();
			client.getConfig();
			System.out.println("c..");
            List<ApplicationReport> list = client.getApplications();//卡这。
            ApplicationReport report = list.get(1);
            System.out.println(report.getApplicationId());
            System.out.println(report.getApplicationType());
            System.out.println(report.getHost());
            System.out.println(report.getName());
            System.out.println(report.getFinalApplicationStatus());
            System.out.println(report.getYarnApplicationState());
            
            GetApplicationReportRequest req =  new GetApplicationReportRequestPBImpl();
//            req.setApplicationId();
            
            //	select count(1) from test2(Stage-1)
            
            System.err.println(client.getName());
            
            
        System.exit(1);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private static final boolean isSecureVerson = true;

	private static final String HIVE_DRIVER = "org.apache.hive.jdbc.HiveDriver";

	private static final String ZOOKEEPER_DEFAULT_LOGIN_CONTEXT_NAME = "Client";
	private static final String ZOOKEEPER_SERVER_PRINCIPAL_KEY = "zookeeper.server.principal";
	private static final String ZOOKEEPER_DEFAULT_SERVER_PRINCIPAL = "zookeeper/hadoop";

	private static Configuration CONF = null;
	private static String KRB5_FILE = null;
	private static String USER_NAME = null;
	private static String USER_KEYTAB_FILE = null;
	private static String zkQuorum = null;
	
	
	private static YarnClient client;  
    protected PrintStream sysout = System.out; 
    
	@Before
	public void init() throws Exception {
		CONF = new Configuration();
		// 其中，zkQuorum的"xxx.xxx.xxx.xxx"为集群中Zookeeper所在节点的IP，端口默认是24002
		zkQuorum = "192.168.0.13:24002,192.168.0.14:24002,192.168.0.15:24002";
		// 设置新建用户的USER_NAME，其中"xxx"指代之前创建的用户名，例如创建的用户为user，则USER_NAME为user
		USER_NAME = "dev_root";
		// 设置客户端的keytab和krb5文件路径
		String userdir = System.getProperty("user.dir") + File.separator + "conf" + File.separator;
		USER_KEYTAB_FILE = userdir + "user.keytab";
		KRB5_FILE = userdir + "krb5.conf";
		
		CONF.addResource(new Path(userdir + "core-site.xml"));
		CONF.addResource(new Path(userdir + "hdfs-site.xml"));
		CONF.addResource(new Path(userdir + "hbase-site.xml"));
		
		LoginUtil.setJaasConf(ZOOKEEPER_DEFAULT_LOGIN_CONTEXT_NAME, USER_NAME, USER_KEYTAB_FILE);
		LoginUtil.setZookeeperServerPrincipal(ZOOKEEPER_SERVER_PRINCIPAL_KEY, ZOOKEEPER_DEFAULT_SERVER_PRINCIPAL);

		// 安全模式
		// Zookeeper登录认证
		LoginUtil.login(USER_NAME, USER_KEYTAB_FILE, KRB5_FILE, CONF);
		
		
		
		client = YarnClient.createYarnClient();  
        client.init(CONF);  
        client.start();  
	}
	
	
}
